from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from .models import Teacher
from django.http import JsonResponse
import json

# Create your views here.
@csrf_exempt
def teacher_list_create(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        teacher = Teacher.objects.create(name=name)
    return JsonResponse(True, safe=False)

# 实现教师的修改和删除
@csrf_exempt
def teacher_ud(request, pk):
    try:
        teacher = Teacher.objects.get(pk=pk)
    except Teacher.DoesNotExist:
        return JsonResponse({'error': 'Teacher not found'}, status=404)

    if request.method == 'PUT':
        try:
            data = json.loads(request.body)
            name = data.get('name')
        except Exception:
            name = request.POST.get('name')

        if not name:
            return JsonResponse({'error': 'Missing name field'}, status=400)

        teacher.name = name
        teacher.save()
        return JsonResponse({'id': teacher.id, 'name': teacher.name})

    elif request.method == 'DELETE':
        Teacher.objects.filter(pk=pk).delete()
        return JsonResponse({'success': True})

    else:
        # 支持 GET 查询单个 Teacher 详情
        return JsonResponse({
            'id': teacher.id,
            'name': teacher.name,
            'created_at': teacher.created_at,
            'updated_at': teacher.updated_at,
        })
